package name_service;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class NameServer extends Thread {
    private final int MAX_CONNECTIONS = 15;
    private int connectionCount;
    private ServerSocket serverSocket;
    private Socket connectionSocket;
    private Map<String,NameServiceMessage> nameDict = new HashMap<String,NameServiceMessage>();
    public static boolean DEBUGGER = true;

    public NameServer(int port) throws IOException {
       serverSocket = new ServerSocket(port);
    }

    @Override
    public void run() {
        try {
            while (!isInterrupted()) {
                if (connectionCount < MAX_CONNECTIONS) {
                    connectionSocket = serverSocket.accept();
                    if(DEBUGGER) System.out.println("Client connected: " + connectionSocket.getInetAddress().toString());
                    (new NameServerCom(this, connectionSocket)).start();
                } else {
                    try {

                        sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close();
        }
    }

    public void close() {
        System.out.println("Socket Close");
        try {
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public synchronized void addConnection() {
        connectionCount++;
    }

    public synchronized void removeConnection() {
        connectionCount--;
    }

    public synchronized void rebind(String name,NameServiceMessage reference){
        nameDict.put(name,reference);
    }
    public synchronized NameServiceMessage resolve(String name){
        return nameDict.get(name);
    }

    public static void main(String[] args) throws IOException {
        if (args.length == 1) {
            if(DEBUGGER) System.out.println("Namensservice gestartet mit Port " + Integer.parseInt(args[0]));
            new NameServer(Integer.parseInt(args[0])).start();
        } else {
            if(DEBUGGER) System.out.println("Namensservice gestartet mit Port default Port 20000");
            new NameServer(20000).start();
        }
    }
}
